use log::{info, warn};
use reqwest::Client;
use std::time::Duration;

/// 代理检测结果
#[derive(Debug)]
pub struct ProxyCheckResult {
    #[allow(dead_code)]
    pub proxy_url: String,
    pub is_available: bool,
    pub error_message: Option<String>,
    pub response_time_ms: Option<u64>,
}

/// 代理检测器
pub struct ProxyChecker {
    timeout_seconds: u64,
}

impl ProxyChecker {
    pub fn new(timeout_seconds: u64) -> Self {
        Self { timeout_seconds }
    }

    /// 检测单个代理是否可用
    pub async fn check_proxy(&self, proxy_url: &str) -> ProxyCheckResult {
        let start = std::time::Instant::now();
        
        // 测试URL列表
        let test_urls = vec![
            "http://httpbin.org/ip",
            "https://httpbin.org/ip",
        ];

        // 创建带代理的客户端
        let client_result = Client::builder()
            .proxy(reqwest::Proxy::all(proxy_url).unwrap_or_else(|_| {
                reqwest::Proxy::all("http://invalid").unwrap()
            }))
            .timeout(Duration::from_secs(self.timeout_seconds))
            .danger_accept_invalid_certs(true) // 用于测试，接受无效证书
            .build();

        let client = match client_result {
            Ok(c) => c,
            Err(e) => {
                return ProxyCheckResult {
                    proxy_url: proxy_url.to_string(),
                    is_available: false,
                    error_message: Some(format!("创建客户端失败: {}", e)),
                    response_time_ms: None,
                };
            }
        };

        // 尝试连接测试URL
        let test_urls_len = test_urls.len();
        for (index, test_url) in test_urls.iter().enumerate() {
            match client.get(*test_url).send().await {
                Ok(response) => {
                    if response.status().is_success() {
                        let elapsed = start.elapsed().as_millis() as u64;
                        return ProxyCheckResult {
                            proxy_url: proxy_url.to_string(),
                            is_available: true,
                            error_message: None,
                            response_time_ms: Some(elapsed),
                        };
                    }
                }
                Err(e) => {
                    // 继续尝试下一个URL
                    if index == test_urls_len - 1 {
                        // 最后一个URL也失败了
                        return ProxyCheckResult {
                            proxy_url: proxy_url.to_string(),
                            is_available: false,
                            error_message: Some(format!("连接失败: {}", e)),
                            response_time_ms: None,
                        };
                    }
                }
            }
        }

        ProxyCheckResult {
            proxy_url: proxy_url.to_string(),
            is_available: false,
            error_message: Some("所有测试URL均失败".to_string()),
            response_time_ms: None,
        }
    }

    /// 检测配置中的所有代理
    pub async fn check_all_proxies(&self, config: &crate::config::Config) -> Vec<(String, ProxyCheckResult)> {
        let mut results = Vec::new();

        info!("🔍 开始检测代理可用性...");
        info!("========================================");

        // 注意: 全局代理配置在config根级别，不在schedule中
        // 如果需要支持全局代理，需要修改Config结构

        // 检查每个任务的代理
        for task in &config.tasks {
            if !task.enabled {
                continue;
            }

            // 任务级代理
            if let Some(task_proxy) = &task.proxy {
                let label = format!("任务[{}]", task.name);
                info!("检测 {} 代理...", label);
                let result = self.check_proxy(task_proxy).await;
                self.log_result(&label, task_proxy, &result);
                results.push((label, result));
            }

            // 账号级代理
            for account in &task.accounts {
                if !account.enabled {
                    continue;
                }

                if let Some(account_proxy) = &account.proxy {
                    let label = format!("账号[{}:{}]", task.name, account.nickname);
                    info!("检测 {} 代理...", label);
                    let result = self.check_proxy(account_proxy).await;
                    self.log_result(&label, account_proxy, &result);
                    results.push((label, result));
                }
            }
        }

        info!("========================================");
        info!("✅ 代理检测完成");
        
        // 统计结果
        let total = results.len();
        let available = results.iter().filter(|(_, r)| r.is_available).count();
        let unavailable = total - available;
        
        if total > 0 {
            info!("📊 检测结果: 总计 {} 个代理, {} 个可用, {} 个不可用", 
                  total, available, unavailable);
        } else {
            info!("ℹ️  未配置任何代理");
        }
        info!("");

        results
    }

    /// 记录检测结果日志
    fn log_result(&self, label: &str, proxy_url: &str, result: &ProxyCheckResult) {
        let masked_proxy = crate::utils::mask_proxy_url(proxy_url);
        
        if result.is_available {
            if let Some(time_ms) = result.response_time_ms {
                info!("  ✅ {} 代理可用 (响应时间: {}ms)", label, time_ms);
            } else {
                info!("  ✅ {} 代理可用", label);
            }
        } else {
            let error_msg = result.error_message.as_deref().unwrap_or("未知错误");
            warn!("  ❌ {} 代理不可用: {}", label, error_msg);
            warn!("     代理地址: {}", masked_proxy);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_invalid_proxy() {
        let checker = ProxyChecker::new(5);
        let result = checker.check_proxy("http://invalid-proxy:9999").await;
        assert!(!result.is_available);
    }
}
